﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using NhWeather.Register;
using System.Timers;

namespace NhWeather.nModbusDevice;

public class WeatherData
{
    public static bool IsRun { get; set; } = true;

    private readonly ObservableCollection<BaseRegister> _registers;

    public WeatherData(ObservableCollection<BaseRegister> regs)
    {
        _registers = regs;

        // 创建并配置定时器
        System.Timers.Timer _timer = new(1000)
        {
            AutoReset = true
        }; // 设置间隔为1000毫秒（1秒）
        _timer.Elapsed += (sender, e) =>
        {
            if (IsRun)
            {
                Generate();
            }
            else
            {
                _timer.Stop();
            }
        };
        _timer.Start();
    }

    /// <summary>
    /// 产生数据数据并填到发送帧
    /// </summary>
    public void Generate()
    {
        var inputRegisters = _registers.OfType<InputRegister>().ToList();

        Parallel.ForEach(inputRegisters, reg =>
        {
            reg.Generate();
        });
    }
}
